/**
 * 
 */
package com.zznode.client.wlanpolling.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.io.CopyStreamListener;

import android.os.Environment;

/**
 * @author Jerome
 *
 */
public class FTPUtils {

	public static String download(String host, String port, String username, String password, String dir, String fileName, CopyStreamListener listener) {
		StringBuffer sb = new StringBuffer();
		FTPClient client = new FTPClient();
		try {
			client.connect(host, Integer.parseInt(port));
			int code = client.getReplyCode();
			if (FTPReply.isPositiveCompletion(code)
					&& client.login(username, password)) {
				client.setFileType(FTP.BINARY_FILE_TYPE);
				client.enterLocalPassiveMode();
				File file = new File(Environment.getExternalStorageDirectory(),
						fileName);
				try {
					file.createNewFile();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				String[] dirs = dir.split("/");
				if(dirs != null && dirs.length > 0){
					for(int i = 0; i < dirs.length; i++){
						client.changeWorkingDirectory(dirs[i]);
					}
				}
				InputStream stO = new BufferedInputStream(
						client.retrieveFileStream(fileName),
						client.getBufferSize());

				OutputStream stD = new FileOutputStream(file);

				org.apache.commons.net.io.Util
						.copyStream(
								stO,
								stD,
								client.getBufferSize(),
								org.apache.commons.net.io.CopyStreamEvent.UNKNOWN_STREAM_SIZE,
								listener);
				client.completePendingCommand();
				file.delete();
			} else {
				client.disconnect();
			}
			client.logout();
		} catch (Exception e) {
			sb.append(e.getMessage());
		} finally {
			if (client.isConnected()) {
				try {
					client.disconnect();
				} catch (IOException ioe) {
					// do nothing
				}
			}
		}
		return sb.toString();
	}
	
	public static String upload(String host, String port, String username, String password, File file, String dir, String fileName, CopyStreamListener listener) {
		StringBuffer sb = new StringBuffer();
		FTPClient client = new FTPClient();
		FileInputStream fis = null;
		try {
			client.connect(host, Integer.parseInt(port));
			int code = client.getReplyCode();
			if (FTPReply.isPositiveCompletion(code)
					&& client.login(username, password)) {
				client.setFileType(FTP.BINARY_FILE_TYPE);
				client.enterLocalPassiveMode();
				fis = new FileInputStream(file);
				long size = file.length();
				OutputStream os = client.storeFileStream(fileName);
				org.apache.commons.net.io.Util.copyStream(fis, os, 1024, file.length(), listener);
//				long totalBytesTransferred = 0;
//				byte buf[] = new byte[8192];
//				int bytesRead = fis.read(buf);
//				while (bytesRead != -1) {
//					os.write(buf, 0, bytesRead);
//					bytesRead = fis.read(buf);
//					totalBytesTransferred += bytesRead;
//					if (listener != null) {
//						listener.bytesTransferred(totalBytesTransferred,
//								bytesRead, size);
//					}
//				}
//				fis.close();
//				os.close();
				client.completePendingCommand();

				file.delete();
			} else {
				client.disconnect();
			}
			client.logout();
		} catch (Exception e) {
			sb.append(e.getMessage());
		} finally {
			if (client.isConnected()) {
				try {
					client.disconnect();
				} catch (IOException ioe) {
					// do nothing
				}
			}
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
		}
		return sb.toString();
	}
	
}
